package com.cuiweiyou.happypaint.ui;

import android.content.Intent;
import android.os.Bundle;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cuiweiyou.happypaint.R;
import com.cuiweiyou.happypaint.base.BaseActivity;
import com.cuiweiyou.happypaint.util.FileUtil;
import com.cuiweiyou.happypaint.view.DialogView;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 画图历史记录
 */
public class HistoryActivity extends BaseActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    HistoryAdapter historyAdapter;
    private List<Map<String, String>> allHappyJsons;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);

        initRecyclerView();
        initPictureData();
    }

    @OnClick(R.id.backShapeView)
    public void onAddViewClicked() {
        finish();
    }

    private void initRecyclerView() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setHasFixedSize(true);

        historyAdapter = new HistoryAdapter(onPictureClickListener);
        recyclerView.setAdapter(historyAdapter);
    }

    private void initPictureData() {
        allHappyJsons = FileUtil.getAllHappyJsons(getExternalFilesDir(null));
        historyAdapter.setActionList(allHappyJsons);
    }

    private HistoryAdapter.OnPictureClickListener onPictureClickListener = new HistoryAdapter.OnPictureClickListener() {
        @Override
        public void onPictureClick(int index) {
            Map<String, String> map = allHappyJsons.get(index);
            String json = map.get("json");

            Intent intent = getIntent();
            intent.putExtra("json", json);
            setResult(223, intent);

            finish();
        }

        @Override
        public void onPictureLongClick(int index) {
            DialogView.showDialog(HistoryActivity.this, onSureListener, "删除", index);
        }
    };

    private DialogView.OnSureListener onSureListener = new DialogView.OnSureListener() {
        @Override
        public void onSure(Object obj) {
            int index = (int) obj;
            Map<String, String> map = allHappyJsons.remove(index);
            String timestemp = map.get("timestemp");
            FileUtil.removePic(getExternalFilesDir(null), timestemp);
            historyAdapter.notifyDataSetChanged();
        }

        @Override
        public void onNo(Object obj) {
        }
    };
}
